import { flow, makeObservable, observable } from "mobx"
import { AuthInfo } from "@/models/global-state"
import { get, Resp } from "@/utils/request"
import { message } from "antd"

export class GlobalStateClass {
  authInfo: AuthInfo = {
    user_name: "",
  }

  constructor() {
    makeObservable(this, {
      authInfo: observable,
      getAuthInfo: flow,
    })
  }

  *getAuthInfo(): Generator<Resp<{ user_name: string }>> {
    // @ts-ignore
    const res = (yield get<{ user_name: string }>(
      "/pegasus/api/auth/"
    )) as Resp<{ user_name: string }>

    if (res.status === 4) {
      // TODO jump to login
      console.log("need login")
      this.authInfo.user_name = "need login"
      return
    }

    if (res.status !== 0) {
      message.error(res.message)
      return
    }
    this.authInfo.user_name = res.data.user_name
  }
}

export const GlobalState = new GlobalStateClass()
